package org.jeecg.modules.checkInventory.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.checkInventory.entity.*;
import org.jeecg.modules.checkInventory.service.*;
import org.jeecg.modules.checkInventory.vo.CheckInventoryPage;
import org.jeecg.modules.checkInventoryTask.entity.CheckInventoryTask;
import org.jeecg.modules.checkInventoryTask.service.ICheckInventoryTaskService;
import org.jeecg.modules.inOrder1.entity.InOrder1;
import org.jeecg.modules.inOrder1.service.IInOrder1Service;
import org.jeecg.modules.outOrder1.entity.OutOrder1;
import org.jeecg.modules.outOrder1.service.IOutOrder1Service;
import org.jeecg.modules.reportLabel.entity.ReportLabel;
import org.jeecg.modules.reportLabel.service.IReportLabelService;
import org.jeecg.modules.system.util.ThreadPoolManager;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 仓库盘点
 * @Author: jeecg-boot
 * @Date: 2023-12-18
 * @Version: V1.0
 */
@Api(tags = "仓库盘点")
@RestController
@RequestMapping("/checkInventory/checkInventory")
@Slf4j
public class CheckInventoryController {
    @Autowired
    private ICheckInventoryService checkInventoryService;
    @Autowired
    private ICheckInventoryShelfService checkInventoryShelfService;
    @Autowired
    private ICheckInventorySkuService checkInventorySkuService;
    @Autowired
    private ICheckInventoryResultService checkInventoryResultService;
    @Autowired
    private ICheckInventoryDifferenceService checkInventoryDifferenceService;
    @Autowired
    private IReportLabelService reportLabelService;
    @Autowired
    private ICheckInventoryTaskService checkInventoryTaskService;
    @Autowired
    private ThreadPoolManager threadPoolManager;
    @Autowired
    private IInOrder1Service inOrderService;
    @Autowired
    private IOutOrder1Service outOrderService;

    /**
     * 分页列表查询
     *
     * @param checkInventory
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "仓库盘点-分页列表查询")
    @ApiOperation(value = "仓库盘点-分页列表查询", notes = "仓库盘点-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(CheckInventory checkInventory,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<CheckInventory> queryWrapper = QueryGenerator.initQueryWrapper(checkInventory, req.getParameterMap());
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        queryWrapper.likeRight("sys_org_code", user.getOrgCode());
        Page<CheckInventory> page = new Page<CheckInventory>(pageNo, pageSize);
        IPage<CheckInventory> pageList = checkInventoryService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "盘点任务领取-分页列表查询")
    @ApiOperation(value = "盘点任务领取-分页列表查询", notes = "盘点任务领取-分页列表查询")
    @GetMapping(value = "/list1")
    public Result<?> queryPageList1(CheckInventory checkInventory,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<CheckInventory> queryWrapper = QueryGenerator.initQueryWrapper(checkInventory, req.getParameterMap());
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        queryWrapper.likeRight("sys_org_code", user.getOrgCode());
        queryWrapper.eq("status", 0);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.orderByDesc("effective_date");
        Page<CheckInventory> page = new Page<CheckInventory>(pageNo, pageSize);
        IPage<CheckInventory> pageList = checkInventoryService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /*// 废弃
    @PostMapping("/receive/{station}")
    public Result<?> receive(@PathVariable String station, @RequestBody CheckInventory checkInventory) {
        List<CheckInventoryShelf> shelfList = checkInventoryShelfService.selectByMainId(checkInventory.getInventoryOrder());
        List<CheckInventorySku> skuList = checkInventorySkuService.selectByMainId(checkInventory.getInventoryOrder());
        if ((shelfList == null || shelfList.isEmpty()) && (skuList == null || skuList.isEmpty())) {
            return Result.error("当前单据无可领取任务！");
        }
        Runnable task = () -> {
            saveTask(station, shelfList, skuList);
        };
        threadPoolManager.executeTask(task);
        return Result.OK("领取成功！");
    }*/

    /**
     * 生成盘点任务标签数据
     *
     * @param checkInventory
     * @return
     */
    public Result<?> receiveNew(CheckInventory checkInventory) {
        List<CheckInventoryShelf> shelfList = checkInventoryShelfService.selectByMainId(checkInventory.getId());
        List<CheckInventorySku> skuList = checkInventorySkuService.selectByMainId(checkInventory.getId());
        if ((shelfList == null || shelfList.isEmpty()) && (skuList == null || skuList.isEmpty())) {
            return Result.error("当前单据无可领取任务！");
        }
        LambdaQueryWrapper<ReportLabel> reportLabelLqw = Wrappers.lambdaQuery(ReportLabel.class);
        reportLabelLqw.in(ReportLabel::getStatus, 3, 5, 6, 8, 12);//已上架；带备货；已备货；
        reportLabelLqw.eq(ReportLabel::getIsFreeze, 0);//未冻结
        if (shelfList != null && !shelfList.isEmpty()) {
            List<String> shelfCodes = shelfList.stream().map(CheckInventoryShelf::getShelfCode).collect(Collectors.toList());
            reportLabelLqw.in(ReportLabel::getShelfCode, shelfCodes);
        }
        if (skuList != null && !skuList.isEmpty()) {
            List<String> skuCodes = skuList.stream().map(CheckInventorySku::getSkuCode).collect(Collectors.toList());
            reportLabelLqw.in(ReportLabel::getSkuCode1, skuCodes).or().in(ReportLabel::getSkuCode2, skuCodes);
        }
        List<ReportLabel> reportLabels = reportLabelService.list(reportLabelLqw);//任务标签
        if (reportLabels.isEmpty()) {
            return Result.error("盘点命中数据为空！请核验后再次提交！");
        }
        List<CheckInventoryTask> checkInventoryTasks = reportLabels.stream().map(item -> {
            CheckInventoryTask checkInventoryTask = new CheckInventoryTask();
            checkInventoryTask.setShelfCode(item.getShelfCode());
            checkInventoryTask.setCompartmentCode(item.getCompartmentCode());
            checkInventoryTask.setSkuCode(item.getSkuCode1());
            checkInventoryTask.setBarCode(item.getBarCode());
            checkInventoryTask.setStatus(0);
            checkInventoryTask.setLabelNumber(item.getLabelNumber());
            checkInventoryTask.setCustomerCode(item.getCustomerCode());
            checkInventoryTask.setInventoryOrder(checkInventory.getId());
            return checkInventoryTask;
        }).collect(Collectors.toList());
        checkInventoryTaskService.saveBatch(checkInventoryTasks);
//        Runnable task = () -> {
//            saveTask(station, shelfList, skuList);
//        };
//        threadPoolManager.executeTask(task);
        return Result.OK("生成盘点任务标签数据成功！");
    }

    /*private void saveTask(String station, List<CheckInventoryShelf> shelfList, List<CheckInventorySku> skuList) {
        List<ReportLabel> labels = getReportLabels();
        Map<String, CheckInventoryTask> taskMap = new HashMap<>();
        if (shelfList != null) {
            shelfList.forEach(shelf -> {
                String shelfCode = shelf.getShelfCode();
                labels.stream()
                        .filter(label -> label.getShelfCode().equals(shelfCode))
                        .forEach(label -> {
                            String labelNumber = label.getLabelNumber();
                            if (!taskMap.containsKey(labelNumber)) {
                                CheckInventoryTask task = new CheckInventoryTask();
                                task.setShelfCode(shelfCode)
                                        .setCompartmentCode(label.getCompartmentCode())
//										 .setSkuCode(label.getSkuCode())
                                        .setCustomerCode(label.getCustomerCode())
                                        .setStationCode(station)
                                        .setStatus(0)
                                        .setLabelNumber(labelNumber);
                                taskMap.put(labelNumber, task);
                            }
                        });
            });
        }
        if (skuList != null) {
            skuList.forEach(sku -> {
                String skuCode = sku.getSkuCode();
                String customerCode = sku.getCustomerCode();
                labels.stream()
                        .filter(label -> label.getSkuCode1().equals(skuCode) && label.getCustomerCode().equals(customerCode))
                        .forEach(label -> {
                            String labelNumber = label.getLabelNumber();
                            if (!taskMap.containsKey(labelNumber)) {
                                CheckInventoryTask task = new CheckInventoryTask();
                                task.setShelfCode(label.getShelfCode())
                                        .setCompartmentCode(label.getCompartmentCode())
                                        .setSkuCode(skuCode)
                                        .setCustomerCode(customerCode)
                                        .setStationCode(station)
                                        .setStatus(0)
                                        .setLabelNumber(labelNumber);
                                taskMap.put(labelNumber, task);
                            }
                        });
            });
        }
        checkInventoryTaskService.saveBatch(new ArrayList<>(taskMap.values()));
    }*/

    /**
     * 添加
     *
     * @param checkInventoryPage
     * @return
     */
    @AutoLog(value = "仓库盘点-添加")
    @ApiOperation(value = "仓库盘点-添加", notes = "仓库盘点-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody CheckInventoryPage checkInventoryPage) {
        CheckInventory checkInventory = new CheckInventory();
        BeanUtils.copyProperties(checkInventoryPage, checkInventory);
        checkInventory.setStatus(0);
        checkInventoryService.saveMain(checkInventory, checkInventoryPage.getCheckInventoryShelfList(), checkInventoryPage.getCheckInventorySkuList(), checkInventoryPage.getCheckInventoryResultList(), checkInventoryPage.getCheckInventoryDifferenceList());
        Result<?> result = receiveNew(checkInventory);
        if (result.isSuccess()) {
            return Result.OK("添加成功！");
        }
        delete(checkInventory.getId());
        return result;
    }

    /**
     * 编辑
     *
     * @param checkInventoryPage
     * @return
     */
    @AutoLog(value = "仓库盘点-编辑")
    @ApiOperation(value = "仓库盘点-编辑", notes = "仓库盘点-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CheckInventoryPage checkInventoryPage) {
        CheckInventory checkInventory = new CheckInventory();
        BeanUtils.copyProperties(checkInventoryPage, checkInventory);
        CheckInventory checkInventoryEntity = checkInventoryService.getById(checkInventory.getId());
        if (checkInventoryEntity == null) {
            return Result.error("未找到对应数据");
        }
        checkInventoryService.updateMain(checkInventory, checkInventoryPage.getCheckInventoryShelfList(), checkInventoryPage.getCheckInventorySkuList(), checkInventoryPage.getCheckInventoryResultList(), checkInventoryPage.getCheckInventoryDifferenceList());
        return Result.OK("编辑成功!");
    }

    public void onCallback(CheckInventory checkInventory) {
        // 创建一个任务
        Runnable task = () -> {
            syncDealResult(checkInventory);
        };
        // 调用线程池执行任务
        threadPoolManager.executeTask(task);
    }

    public void syncDealResult(CheckInventory checkInventory) {
        CheckInventoryTask checkInventoryTask = new CheckInventoryTask();

    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "仓库盘点-通过id删除")
    @ApiOperation(value = "仓库盘点-通过id删除", notes = "仓库盘点-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        checkInventoryService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "仓库盘点-批量删除")
    @ApiOperation(value = "仓库盘点-批量删除", notes = "仓库盘点-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.checkInventoryService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "仓库盘点-通过id查询")
    @ApiOperation(value = "仓库盘点-通过id查询", notes = "仓库盘点-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        CheckInventory checkInventory = checkInventoryService.getById(id);
        if (checkInventory == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(checkInventory);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "盘点货架通过主表ID查询")
    @ApiOperation(value = "盘点货架主表ID查询", notes = "盘点货架-通主表ID查询")
    @GetMapping(value = "/queryCheckInventoryShelfByMainId")
    public Result<?> queryCheckInventoryShelfListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<CheckInventoryShelf> checkInventoryShelfList = checkInventoryShelfService.selectByMainId(id);
        return Result.OK(checkInventoryShelfList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "盘点品番通过主表ID查询")
    @ApiOperation(value = "盘点品番主表ID查询", notes = "盘点品番-通主表ID查询")
    @GetMapping(value = "/queryCheckInventorySkuByMainId")
    public Result<?> queryCheckInventorySkuListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<CheckInventorySku> checkInventorySkuList = checkInventorySkuService.selectByMainId(id);
        return Result.OK(checkInventorySkuList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "盘点结果通过主表ID查询")
    @ApiOperation(value = "盘点结果主表ID查询", notes = "盘点结果-通主表ID查询")
    @GetMapping(value = "/queryCheckInventoryResultByMainId")
    public Result<?> queryCheckInventoryResultListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<CheckInventoryResult> checkInventoryResultList = checkInventoryResultService.selectByMainId(id);
        return Result.OK(checkInventoryResultList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "盘点差异通过主表ID查询")
    @ApiOperation(value = "盘点差异主表ID查询", notes = "盘点差异-通主表ID查询")
    @GetMapping(value = "/queryCheckInventoryDifferenceByMainId")
    public Result<?> queryCheckInventoryDifferenceListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<CheckInventoryDifference> checkInventoryDifferenceList = checkInventoryDifferenceService.selectByMainId(id);
        return Result.OK(checkInventoryDifferenceList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param checkInventory
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CheckInventory checkInventory) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<CheckInventory> queryWrapper = QueryGenerator.initQueryWrapper(checkInventory, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<CheckInventory> queryList = checkInventoryService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<CheckInventory> checkInventoryList = new ArrayList<CheckInventory>();
        if (oConvertUtils.isEmpty(selections)) {
            checkInventoryList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            checkInventoryList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<CheckInventoryPage> pageList = new ArrayList<CheckInventoryPage>();
        for (CheckInventory main : checkInventoryList) {
            CheckInventoryPage vo = new CheckInventoryPage();
            BeanUtils.copyProperties(main, vo);
            List<CheckInventoryShelf> checkInventoryShelfList = checkInventoryShelfService.selectByMainId(main.getId());
            vo.setCheckInventoryShelfList(checkInventoryShelfList);
            List<CheckInventorySku> checkInventorySkuList = checkInventorySkuService.selectByMainId(main.getId());
            vo.setCheckInventorySkuList(checkInventorySkuList);
            List<CheckInventoryResult> checkInventoryResultList = checkInventoryResultService.selectByMainId(main.getId());
            vo.setCheckInventoryResultList(checkInventoryResultList);
            List<CheckInventoryDifference> checkInventoryDifferenceList = checkInventoryDifferenceService.selectByMainId(main.getId());
            vo.setCheckInventoryDifferenceList(checkInventoryDifferenceList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "仓库盘点列表");
        mv.addObject(NormalExcelConstants.CLASS, CheckInventoryPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("仓库盘点数据", "导出人:" + sysUser.getRealname(), "仓库盘点"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CheckInventoryPage> list = ExcelImportUtil.importExcel(file.getInputStream(), CheckInventoryPage.class, params);
                for (CheckInventoryPage page : list) {
                    CheckInventory po = new CheckInventory();
                    BeanUtils.copyProperties(page, po);
                    checkInventoryService.saveMain(po, page.getCheckInventoryShelfList(), page.getCheckInventorySkuList(), page.getCheckInventoryResultList(), page.getCheckInventoryDifferenceList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    /*private List<ReportLabel> getReportLabels() {
        LambdaQueryWrapper<ReportLabel> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ReportLabel::getStatus, "1");
        wrapper.eq(ReportLabel::getIsFreeze, 0);
        return reportLabelService.list(wrapper);
    }*/

    /**
     * 移动端-我的任务
     *
     * @return
     */
    @AutoLog(value = "移动端-我的任务")
    @ApiOperation(value = "移动端-我的任务", notes = "移动端-我的任务")
    @GetMapping(value = "/getMyTask")
    public Result<?> getMyTask() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String realname = loginUser.getRealname();
        String orgCode = loginUser.getOrgCode();
        //查询关联的入库单/出库单/盘点单
        LambdaQueryWrapper<InOrder1> inOrder1Lqw = Wrappers.lambdaQuery(InOrder1.class);
        LambdaQueryWrapper<OutOrder1> outOrder1Lqw = Wrappers.lambdaQuery(OutOrder1.class);
        LambdaQueryWrapper<CheckInventory> checkInventoryLqw = Wrappers.lambdaQuery(CheckInventory.class);
        inOrder1Lqw.eq(InOrder1::getTallyClerk, realname).or().eq(InOrder1::getTruckDriver, realname);
        inOrder1Lqw.orderByAsc(InOrder1::getInOrderStatus);
        outOrder1Lqw.eq(OutOrder1::getTallyClerk, realname).or().eq(OutOrder1::getTruckDriver, realname);
        outOrder1Lqw.orderByAsc(OutOrder1::getOutOrderStatus);
        checkInventoryLqw.likeRight(CheckInventory::getSysOrgCode, orgCode);
        checkInventoryLqw.orderByAsc(CheckInventory::getStatus);
        List<InOrder1> inOrder1s = inOrderService.list(inOrder1Lqw);
        List<OutOrder1> outOrder1s = outOrderService.list(outOrder1Lqw);
        List<CheckInventory> checkInventories = checkInventoryService.list(checkInventoryLqw);
        Map<String, List<?>> map = new HashMap<>();
        map.put("inOrder", inOrder1s);
        map.put("outOrder", outOrder1s);
        map.put("checkInventory", checkInventories);
        return Result.OK(map);
    }

    /**
     * 移动端-盘点单任务详情
     *
     * @return
     */
    @AutoLog(value = "移动端-盘点单任务详情")
    @ApiOperation(value = "移动端-盘点单任务详情", notes = "移动端-盘点单任务详情")
    @GetMapping(value = "/getTaskDetail")
    public Result<?> getTaskDetail(@RequestParam(name = "id", required = true) String id) {
        LambdaQueryWrapper<CheckInventoryTask> checkInventoryTaskLqw = Wrappers.lambdaQuery(CheckInventoryTask.class);
        checkInventoryTaskLqw.eq(CheckInventoryTask::getInventoryOrder, id);
        List<CheckInventoryTask> checkInventoryTasks = checkInventoryTaskService.list(checkInventoryTaskLqw);
        return Result.OK(checkInventoryTasks);
    }

    /**
     * 移动端-盘点操作
     *
     * @return
     */
    @AutoLog(value = "移动端-盘点操作")
    @ApiOperation(value = "移动端-盘点操作", notes = "移动端-盘点操作")
    @PutMapping(value = "/inventoryOperation")
    public Result<?> inventoryOperation(@RequestParam(name = "checkInventoryId", required = true) String checkInventoryId, @RequestParam(name = "barCode", required = true) String barCode) {
        // 1.0 判断盘点单状态
        CheckInventory checkInventory = checkInventoryService.getById(checkInventoryId);//盘点单
        List<CheckInventorySku> checkInventorySkus = checkInventorySkuService.selectByMainId(checkInventoryId);//盘点品番
        if (!checkInventory.getStatus().equals(0) && !checkInventory.getStatus().equals(1)) {
            return Result.error("盘点单状态错误，禁止操作！");
        }
        if (checkInventory.getEffectiveDate().compareTo(new Date()) > 0) {
            return Result.error("盘点单尚未生效，禁止操作！");
        }
        // 2.0 盘点操作
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String realname = loginUser.getRealname();
        LambdaQueryWrapper<CheckInventoryTask> checkInventoryTaskLqw = Wrappers.lambdaQuery(CheckInventoryTask.class);
        checkInventoryTaskLqw.eq(CheckInventoryTask::getInventoryOrder, checkInventoryId);
        checkInventoryTaskLqw.eq(CheckInventoryTask::getBarCode, barCode);
        CheckInventoryTask checkInventoryTask = checkInventoryTaskService.getOne(checkInventoryTaskLqw);

        if (Objects.isNull(checkInventoryTask)) {
            //判断品番是否符合
            if (!checkInventorySkus.isEmpty()) {
                ReportLabel reportLabel = reportLabelService.getByCode(barCode);
                boolean skuExists = checkInventorySkus.stream()
                        .anyMatch(sku -> sku.getSkuCode().equals(reportLabel.getSkuCode1()) || sku.getSkuCode().equals(reportLabel.getSkuCode2()));
                if (!skuExists) {
                    return Result.error("该品番无需盘点，请核对后再操作！");
                }
            }
            // 无任务数据，添加
            CheckInventoryTask task = new CheckInventoryTask();
            task.setBarCode(barCode);
            task.setInventoryOrder(checkInventoryId);
            task.setStatus(2);//盘盈标记
            task.setFinishMan(realname);
            task.setFinishTime(new Date());
            checkInventoryTaskService.save(task);
        }else {
            // 禁止重复扫码
            if (checkInventoryTask.getStatus().equals(1) || checkInventoryTask.getStatus().equals(2)) {
                return Result.error("该标签已作业，禁止操作！");
            }
            // 有任务数据，修改
            checkInventoryTask.setStatus(1);
            checkInventoryTask.setFinishMan(realname);
            checkInventoryTask.setFinishTime(new Date());
            checkInventoryTaskService.updateById(checkInventoryTask);
        }

        // 3.0 修改盘点单状态
        if (checkInventory.getStatus() == 0) {
            checkInventory.setStatus(1);//进行中
            checkInventoryService.updateById(checkInventory);
        }
        return Result.OK("扫码成功！");
    }

    /**
     * 移动端-盘点结束
     *
     * @return
     */
    @AutoLog(value = "移动端-盘点结束")
    @ApiOperation(value = "移动端-盘点结束", notes = "移动端-盘点结束")
    @PutMapping(value = "/inventoryEnd")
    public Result<?> inventoryEnd(@RequestParam(name = "checkInventoryId", required = true) String checkInventoryId) {
        // 1.0 查看盘点单关联任务完成情况
        LambdaQueryWrapper<CheckInventoryTask> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CheckInventoryTask::getInventoryOrder, checkInventoryId);
        wrapper.in(CheckInventoryTask::getStatus, 0,1);
        List<CheckInventoryTask> list1 = checkInventoryTaskService.list(wrapper);
        wrapper.clear();
        wrapper.eq(CheckInventoryTask::getInventoryOrder, checkInventoryId);
        wrapper.in(CheckInventoryTask::getStatus, 1,2);
        List<CheckInventoryTask> list2 = checkInventoryTaskService.list(wrapper);
        // 2.0 添加盘点结果数据
        CheckInventoryResult checkInventoryResult = new CheckInventoryResult();
        checkInventoryResult.setInventoryOrder(checkInventoryId);
        checkInventoryResult.setNumber(list1.size());
        checkInventoryResult.setRealNumber(list2.size());
        checkInventoryResultService.save(checkInventoryResult);
        // 3.0 如有盘亏/盘盈异常，添加盘点差异数据
        if (list1.size() != list2.size()){
            wrapper.clear();
            wrapper.eq(CheckInventoryTask::getInventoryOrder, checkInventoryId);
            wrapper.in(CheckInventoryTask::getStatus, 0,2);
            List<CheckInventoryTask> list = checkInventoryTaskService.list(wrapper);
            List<CheckInventoryDifference> differenceList = new ArrayList<>();
            for (CheckInventoryTask checkInventoryTask : list){
                CheckInventoryDifference checkInventoryDifference = new CheckInventoryDifference();
                BeanUtils.copyProperties(checkInventoryTask, checkInventoryDifference);
                differenceList.add(checkInventoryDifference);
            }
            checkInventoryDifferenceService.saveBatch(differenceList);
        }
        // 4.0 修改盘点单状态
        CheckInventory byId = checkInventoryService.getById(checkInventoryId);
        byId.setStatus(2);
        checkInventoryService.updateById(byId);
        return Result.OK("盘点结束成功！");
    }

}
